/**
 * aes encode and decode utils
 */
let aesUtils = module.exports = {};
let crypto = require('crypto');
let config = require('config');
let base64 = require('js-base64').Base64;


aesUtils.encode = function (data) {
    //let cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    let cipher = crypto.createCipheriv(config.aes.algorithm, config.aes.key, config.aes.iv);
    let crypted = cipher.update(data, config.aes.clearEncoding, config.aes.cipherEncoding);
    crypted += cipher.final(config.aes.cipherEncoding);

    return crypted;
};

aesUtils.decode = function (cipherText) {
    if (!cipherText) {
        return null;
    }
    let decipher = crypto.createDecipheriv(config.aes.algorithm, config.aes.key, config.aes.iv);
    let decoded = decipher.update(cipherText, config.aes.cipherEncoding, config.aes.clearEncoding);
    decoded += decipher.final(config.aes.clearEncoding);

    return decoded;
};